using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Collections;
using UMC.Web;
using UMC.Data;
using UMC.Web.UI;
using UMC.Net;
using System.Linq;

namespace UMC.ITME.Activities
{

    /// <summary>
    /// 构建原生应用
    /// </summary>
    [Apiumc("ITME", "Builder", Desc = "构建原生应用", Auth = WebAuthType.All)]
    class SiteBuilderActivity : UMC.Web.WebActivity
    {
        const string AppConfigKey = "AppConfig";
        public override void ProcessActivity(WebRequest request, WebResponse response)
        {
            var secret = UMC.Data.WebResource.Instance().Provider["appSecret"];
            if (String.IsNullOrEmpty(secret))
            {
                this.Prompt("当前版本未登记注册", false);
                this.Context.Response.Redirect("System", "License");
            }
            var appConf = UMC.Data.DataFactory.Instance().Config<Hashtable>(AppConfigKey) ?? new Hashtable();
            if (appConf.Count == 0)
            {

                var webr = new Uri(APIProxy.Uri, "Transfer").WebRequest();
                UMC.ITME.Utility.Sign(webr, secret);
                var xhr = webr.Get();

                var meta = JSON.Deserialize<WebMeta>(xhr.ReadAsString()) ?? new WebMeta();
                appConf["AppName"] = meta["caption"] ?? "IT管理引擎";
                appConf["BgSrc"] = "https://www.apiumc.com/Apps/bg.png";
                appConf["IconSrc"] = "https://www.apiumc.com/Apps/icon.png";
                appConf["Config"] = new WebMeta().Put("footBar", new List<WebMeta>
                    {
                        new WebMeta().Put("text", "云桌面", "key", "Pager", "cmd", "UI", "model", "ITME", "icon", "\uf1b3", "RefreshEvent", "ITME.Site,User"),
                        new WebMeta("text", "发布应用", "icon", "\ue907").Put("max", true).Put("click", new UIClick("ITME", "Setup")),
                        new WebMeta().Put("text", "我的", "key", "Pager", "cmd", "Self", "model", "Account", "icon", "", "RefreshEvent", "UI.Setting").Put("search", new WebMeta("Type", "Setting"))
                    }).Put("dataEvent", new WebMeta().Put("Login", new UIClick("Account", "Login")));

                UMC.Data.DataFactory.Instance().Config(AppConfigKey, appConf);
                response.Redirect(request.Model, request.Command);

            }
            var model = this.AsyncDialog("Edit", r =>
            {
                var Discount = new UIHeader.Portrait(appConf["IconSrc"] as string);

                Discount.Desc(appConf["AppName"] as string);

                var color = 0xfe314e;
                var header = new UIHeader();
                var title = UITitle.Create();
                title.Title = "原生应用";
                title.Style.BgColor(color);
                title.Style.Color(0xfff);
                Discount.Gradient(color, color);

                var style = new UIStyle();
                style.Name("desc").Click(new UIClick(request, r, "AppName"));
                style.Name("image-radius", "10");
                header.AddPortrait(Discount, style);
                Discount.Click(new UIClick(request, r, "IconSrc"));
                var ui = UISection.Create(header, title);


                var Config = (appConf["Config"] as Hashtable) ?? new Hashtable();
                var BgSrc = appConf["BgSrc"] as string;

                ui.AddCell("域名", request.Url.Host);
                ui.AddCell("启动图", String.IsNullOrEmpty(BgSrc) ? "未设置" : "已设置", new UIClick(request, r, "BgSrc"));
                var nui = ui.NewSection();
                nui.Header.Put("text", "基本色");
                var c = UICell.UI("标题背景色", Config["titleBgColor"] as string ?? "#3199e8", "◉", new UIClick(request, r, "titleBgColor"));
                c.Style.Name("value").Name("color", Config["titleBgColor"] as string ?? "#3199e8");
                nui.Add(c);

                c = UICell.UI("标题文本色", Config["titleColor"] as string ?? "#fff", "◉", new UIClick(request, r, "titleColor"));
                c.Style.Name("value").Name("color", Config["titleColor"] as string ?? "#fff");
                nui.Add(c);

                c = UICell.UI("醒目文本色", Config["priceColor"] as string ?? "#ef4f4f", "◉", new UIClick(request, r, "priceColor"));
                c.Style.Name("value").Name("color", Config["priceColor"] as string ?? "#ef4f4f");
                nui.Add(c);


                var btn = Config["button"] as Hashtable ?? new Hashtable();
                nui = nui.NewSection();
                nui.Header.Put("text", "按钮基本色");
                c = UICell.UI("按钮背景色", btn["color"] as string ?? "#04be02", "◉", new UIClick(request, r, "button.color"));
                c.Style.Name("value").Name("color", btn["color"] as string ?? "#04be02");
                nui.Add(c);

                c = UICell.UI("按钮高亮色", btn["highlighted"] as string ?? "#039702", "◉", new UIClick(request, r, "button.highlighted"));
                c.Style.Name("value").Name("color", btn["highlighted"] as string ?? "#039702");
                nui.Add(c);

                btn = Config["tabBar"] as Hashtable ?? new Hashtable();

                nui = nui.NewSection();

                nui.Header.Put("text", "图标基本色");
                c = UICell.UI("图标基本色", btn["color"] as string ?? "#04be02", "◉", new UIClick(request, r, "tabBar.color"));
                c.Style.Name("value").Name("color", btn["color"] as string ?? "#04be02");
                nui.Add(c);

                c = UICell.UI("图标选中色", btn["highlighted"] as string ?? "#039702", "◉", new UIClick(request, r, "tabBar.highlighted"));
                c.Style.Name("value").Name("color", btn["highlighted"] as string ?? "#039702");
                nui.Add(c);


                nui = nui.NewSection();

                nui.AddCell("路径检索", Config.ContainsKey("webnav") ? "已设置" : "未设置", new UIClick(request, r, "webnav"));
                nui.AddCell("默认搜索", Config.ContainsKey("search") ? "已设置" : "未设置", new UIClick(request, r, "search"));
                nui.AddCell("欢迎页面", Config.ContainsKey("welcome") ? "已设置" : "未设置", new UIClick(request, r, "welcome"));


                nui = nui.NewSection();
                nui.AddCell("事件响应", new UIClick(request, r, "dataEvent"));//webnav

                btn = Config["dataEvent"] as Hashtable ?? new Hashtable();
                if (btn.Count > 0)
                {
                    var dataem = btn.GetEnumerator();
                    while (dataem.MoveNext())
                    {
                        var cell = UI.UI(dataem.Key.ToString(), "", new UIClick(request, r, $"dataEvent.{dataem.Key}"));
                        nui.Delete(cell, new UIEventText().Click(new UIClick(request, r, $"dataEvent.{dataem.Key}.DEL")));
                    }
                }
                nui = nui.NewSection();

                nui.AddCell("首页页面", new UIClick(request, r, "footBar"));

                var footBar = Config["footBar"] as Array;
                if (footBar == null)
                {
                    footBar = new Object[0];
                }
                if (footBar.Length > 0)
                {
                    var dataem = footBar.GetEnumerator();
                    for (int i = 0; i < footBar.Length; i++)
                    {
                        var h = footBar.GetValue(i) as Hashtable;
                        var icon = h["icon"] as string;
                        if (String.IsNullOrEmpty(icon))
                        {
                            icon = "\uf216";
                        }
                        var cell = UI.UI(icon[0], h["text"] as String, h["key"] as string ?? "Click", new UIClick(request, r, $"footBar.{i}"));
                        nui.Delete(cell, new UIEventText().Click(new UIClick(request, r, $"footBar.{i}.DEL")));
                    }
                }


                var btnName = "生成应用";

                ui.UIFootBar = new UIFootBar();
                ui.UIFootBar.IsFixed = true;
                ui.UIFootBar.AddText(new UIEventText(btnName).Style(new UIStyle().BgColor())
                    .Click(new UIClick(request, r, "Builder")), new UIEventText("应用下载")
                    .Click(new UIClick(request, r, "Download")));

                ui.SendTo(this.Context, $"{request.Model}.{request.Command}", $"{request.Model}.{request.Command}.View");
                // response(ui);
            });
            if (model == "Info")
            {
                appConf.Remove("Config");

                var appId = Utility.Guid(WebResource.Instance().Provider["appId"]).Value;
                appConf["Key"] = Utility.Parse36Encode(Utility.IntParse(appId));
                response.Redirect(appConf);

            }
            else if (request.IsMaster == false)
            {
                this.Prompt("管理员才能管理原生应用的各项配置");
            }

            var Config = (appConf["Config"] as Hashtable) ?? new Hashtable();
            appConf["Config"] = Config;
            switch (model)
            {
                case "Builder":
                    {
                        var webr = UMC.ITME.Utility.Sign(new Uri(APIProxy.Uri, "Transfer").WebRequest(), secret).Put(new WebMeta().Put("type", "Builder").Put("AppConfig", appConf));

                        var str = webr.ReadAsString();

                        var meta = JSON.Deserialize<WebMeta>(str) ?? new WebMeta();
                        this.Prompt("提示", meta["msg"]);
                    }
                    break;
                case "AppName":
                    appConf["AppName"] = this.AsyncDialog("AppName", r => new UITextDialog() { Title = "App名称", DefaultValue = appConf["AppName"] as string });


                    UMC.Data.DataFactory.Instance().Config(AppConfigKey, appConf);

                    this.Context.Send($"{request.Model}.{request.Command}.View", true);
                    break;

                case "BgSrc":
                    this.AsyncDialog("Type", r => new UISheetDialog() { Title = "启动图" }.Put(new UIClick(appConf["BgSrc"] as string) { Key = "Browser", Text = "查看" }).Put("上传", "Upload"));
                    this.AsyncDialog("BgSrc", "System", "Picture", new WebMeta("seq", "BgSrc").Put("id", "apiumc").Put("size", "512x1024"));

                    appConf["BgSrc"] = UMC.Data.WebResource.Instance().ImageResolve(request.Url, "apiumc", "BgSrc", "0", Utility.TimeSpan().ToString());

                    UMC.Data.DataFactory.Instance().Config(AppConfigKey, appConf);


                    this.Context.Send($"{request.Model}.{request.Command}.View", true);
                    break;
                case "IconSrc":

                    this.AsyncDialog("IconSrc", "System", "Picture", new WebMeta("seq", "IconSrc").Put("id", "apiumc").Put("size", "512x512"));
                    appConf["IconSrc"] = UMC.Data.WebResource.Instance().ImageResolve(request.Url, "apiumc", "IconSrc", "0", Utility.TimeSpan().ToString());


                    UMC.Data.DataFactory.Instance().Config(AppConfigKey, appConf);
                    this.Context.Send($"{request.Model}.{request.Command}.View", true);
                    break;
                case "titleBgColor":
                case "priceColor":
                case "titleColor":
                case "button.highlighted":
                case "button.color":
                case "tabBar.highlighted":
                case "tabBar.color":
                    var color = this.AsyncDialog("Color", "System", "Color");

                    var bIndex = model.IndexOf('.');
                    if (bIndex > 0)
                    {
                        var key = model.Substring(0, bIndex);
                        var btn = Config[key] as Hashtable ?? new Hashtable();
                        btn[model.Substring(bIndex + 1)] = color;
                        Config[key] = btn;
                    }
                    else
                    {
                        Config[model] = color;
                    }

                    UMC.Data.DataFactory.Instance().Config(AppConfigKey, appConf);
                    this.Context.Send($"{request.Model}.{request.Command}.View", true);
                    break;
                case "webnav":
                case "search":
                    {
                        var search = this.AsyncDialog("Search", r =>
                        {
                            var s = Config[model] as Hashtable ?? new Hashtable();
                            var d = new UIFormDialog();// { Title = model == "webnav" : "路径检索" };
                            d.AddText("模块", "model", s["model"] as string);
                            d.AddText("指令", "cmd", s["cmd"] as string);
                            if (s.ContainsKey("send"))
                            {
                                d.AddText("参数值", "send", JSON.Serialize(s["send"]).Replace("\"", "").Trim('{', '}')).NotRequired();
                            }
                            else
                            {
                                d.AddText("参数值", "send").NotRequired();
                            }
                            switch (model)
                            {
                                case "webnav":
                                    d.Title = "路径检索";
                                    d.AddFooter("检索只有路径的Url，确认此路径关联的页面");
                                    break;
                                default:
                                    d.Title = "搜索数据源";
                                    d.AddFooter("需要搜索指令返回UISection数据源");
                                    break;
                            }
                            return d;


                        });
                        var searchValue = new Hashtable();
                        searchValue["model"] = search["model"];
                        searchValue["cmd"] = search["cmd"];
                        var send = search["send"];

                        if (String.IsNullOrEmpty(send) == false)
                        {
                            var sds = send.Split(':', ',');
                            searchValue["send"] = new WebMeta(send.Split(new char[] { ':', ',' }, StringSplitOptions.RemoveEmptyEntries));

                        }
                        Config[model] = searchValue;

                        UMC.Data.DataFactory.Instance().Config(AppConfigKey, appConf);

                        this.Context.Send($"{request.Model}.{request.Command}.View", true);
                    }
                    break;
                case "welcome":
                    {

                        var search = this.AsyncDialog("Welcome", r =>
                        {
                            var we = Config[model] as Hashtable ?? new Hashtable();

                            var s = we["click"] as Hashtable ?? new Hashtable();
                            var d = new UIFormDialog() { Title = "欢迎页" };
                            d.AddText("标识", "key", we["key"] as string);
                            d.AddText("模块", "model", s["model"] as string);
                            d.AddText("指令", "cmd", s["cmd"] as string);
                            if (s.ContainsKey("send"))
                            {
                                d.AddText("参数值", "send", JSON.Serialize(s["send"]).Replace("\"", "").Trim('{', '}')).NotRequired();
                            }
                            else
                            {
                                d.AddText("参数值", "send").NotRequired();
                            }
                            d.AddFooter("只要标识没有被记录在本地，才会显示欢迎页");
                            return d;


                        });
                        var searchValue = new Hashtable();
                        searchValue["model"] = search["model"];
                        searchValue["cmd"] = search["cmd"];
                        var send = search["send"];

                        if (String.IsNullOrEmpty(send) == false)
                        {
                            var sds = send.Split(new char[] { ':', ',' }, StringSplitOptions.RemoveEmptyEntries);// send.Split(':', ',');
                            if (sds.Length == 1)
                            {
                                searchValue["send"] = sds[0];
                            }
                            else
                            {
                                searchValue["send"] = new WebMeta(sds);//send.Split(new char[] { ':', ',' }, StringSplitOptions.RemoveEmptyEntries));
                            }
                        }
                        Config[model] = new WebMeta("key", search["key"]).Put("click", searchValue);


                        UMC.Data.DataFactory.Instance().Config(AppConfigKey, appConf);
                        this.Context.Send($"{request.Model}.{request.Command}.View", true);

                    }
                    break;
                case "dataEvent":
                    {

                        var l = model.IndexOf('.');
                        var dataEvent = Config["dataEvent"] as Hashtable ?? new Hashtable();
                        var search = this.AsyncDialog("Welcome", r =>
                        {
                            var s = new Hashtable();
                            if (l > 0)
                            {
                                var sKey = model.Substring(l + 1);
                                if (dataEvent.ContainsKey(sKey))
                                {
                                    s = dataEvent[sKey] as Hashtable ?? new Hashtable();
                                }
                                else if (sKey.EndsWith(".DEL"))
                                {
                                    dataEvent.Remove(sKey.Substring(0, sKey.Length - 4));
                                    Config["dataEvent"] = dataEvent;

                                    UMC.Data.DataFactory.Instance().Config(AppConfigKey, appConf);

                                    this.Context.Send($"{request.Model}.{request.Command}.View", true);//
                                }
                            }

                            var d = new UIFormDialog() { Title = "事件响应" };
                            if (l == -1)
                            {
                                d.AddText("数据事件", "key", String.Empty);
                            }
                            else
                            {
                                d.AddTextValue().Put("数据事件", model.Substring(l + 1));
                            }
                            d.AddText("模块", "model", s["model"] as string);
                            d.AddText("指令", "cmd", s["cmd"] as string);
                            if (s.ContainsKey("send"))
                            {
                                d.AddText("参数值", "send", JSON.Serialize(s["send"]).Replace("\"", "").Trim('{', '}')).NotRequired();
                            }
                            else
                            {
                                d.AddText("参数值", "send").NotRequired();
                            }
                            return d;


                        });
                        var searchValue = new Hashtable();
                        searchValue["model"] = search["model"];
                        searchValue["cmd"] = search["cmd"];
                        var send = search["send"];

                        if (String.IsNullOrEmpty(send) == false)
                        {
                            var sds = send.Split(new char[] { ':', ',' }, StringSplitOptions.RemoveEmptyEntries);// send.Split(':', ',');
                            if (sds.Length == 1)
                            {
                                searchValue["send"] = sds[0];
                            }
                            else
                            {
                                searchValue["send"] = new WebMeta(sds);
                            }
                        }
                        if (l > 0)
                        {

                            dataEvent[model.Substring(l + 1)] = searchValue;
                        }
                        else
                        {

                            dataEvent[search["key"]] = searchValue;
                        }
                        Config["dataEvent"] = dataEvent;

                        UMC.Data.DataFactory.Instance().Config(AppConfigKey, appConf);

                        this.Context.Send($"{request.Model}.{request.Command}.View", true);//


                    }
                    break;
                case "footBar":
                    {
                        var key = "Click";
                        var l = model.IndexOf('.');
                        var dataEvent = Config["footBar"] as Array;// ?? new Array();
                        if (dataEvent == null)
                        {
                            dataEvent = new Object[0];
                        }
                        int index = -1;
                        if (l > 0)
                        {
                            var sIndex = model.Substring(l + 1);
                            var s2 = sIndex.IndexOf('.');
                            if (s2 == -1)
                            {
                                index = Utility.IntParse(sIndex, -1);
                            }
                            else
                            {

                                index = Utility.IntParse(sIndex.Substring(0, s2), -1);//l + 1), -1);

                                var d = new ArrayList();
                                d.AddRange(dataEvent);
                                d.RemoveAt(index);
                                // d.Add(item);
                                dataEvent = d.ToArray();

                                Config["footBar"] = dataEvent;

                                UMC.Data.DataFactory.Instance().Config(AppConfigKey, appConf);

                                this.Context.Send($"{request.Model}.{request.Command}.View", true);

                            }
                        }
                        else //if (dataEvent.Length == 0)
                        {
                            key = this.AsyncDialog("Type", r => new UISheetDialog() { Title = "类型" }.Put("单页面", "Page").Put("复合页", "Tabs").Put("按钮项", "Click"));
                        }
                        var search = this.AsyncDialog("footBar", r =>
                        {
                            var foot = new Hashtable();

                            if (index < dataEvent.Length && index > -1)
                            {
                                foot = dataEvent.GetValue(index) as Hashtable;
                            }
                            var d = new UIFormDialog() { Title = "首页页面" };
                            if (l == -1)
                            {
                                d.AddTextValue().Put("新增类型", key);
                            }
                            else
                            {
                                key = foot["key"] as string ?? "Click";
                                d.AddTextValue().Put("页面类型", key);
                            }
                            d.AddText("标题", "text", foot["text"] as string);
                            d.AddOption("图标", "icon", foot["icon"] as string, foot["icon"] as string).Command("System", "Icon").Put("Icon", true);

                            var s = foot;
                            switch (key)
                            {
                                case "Click":
                                    s = foot["click"] as Hashtable ?? new Hashtable();
                                    break;
                            }
                            d.AddText("模块", "model", s["model"] as string).Put("tip", "");

                            d.AddText("指令", "cmd", s["cmd"] as string);
                            if (s.ContainsKey("send"))
                            {
                                d.AddText("参数值", "send", JSON.Serialize(s["send"]).Replace("\"", "").Trim('{', '}')).NotRequired();
                            }
                            else
                            {
                                d.AddText("参数值", "send").NotRequired();
                            }
                            switch (key)
                            {
                                case "Page":
                                    d.AddText("页面刷新", "RefreshEvent", s["RefreshEvent"] as string).NotRequired();
                                    d.AddFooter("要求单页面指令返回UISection数据源");
                                    break;
                                case "Click":
                                    d.AddCheckBox("", "Max", "no").Put("大按钮", "YES", foot.ContainsKey("max"));
                                    break;
                                case "Tabs":
                                    d.AddFooter("请注意：复合页Tabs要求指令返回的格式");
                                    break;
                            }
                            return d;


                        });

                        var searchValue = new Hashtable();
                        searchValue["model"] = search["model"];
                        searchValue["cmd"] = search["cmd"];
                        var send = search["send"];

                        if (String.IsNullOrEmpty(send) == false)
                        {
                            var sds = send.Split(new char[] { ':', ',' }, StringSplitOptions.RemoveEmptyEntries);// send.Split(':', ',');
                            if (sds.Length == 1)
                            {
                                searchValue["send"] = sds[0];
                            }
                            else
                            {
                                searchValue["send"] = new WebMeta(sds);
                            }
                        }
                        var item = new WebMeta();
                        switch (key)
                        {
                            case "Page":
                                item = new WebMeta(searchValue);
                                item.Put("key", key);
                                var RefreshEvent = search["RefreshEvent"];
                                if (String.IsNullOrEmpty(RefreshEvent) == false)
                                {
                                    item.Put("RefreshEvent", RefreshEvent);
                                }
                                break;
                            case "Tabs":
                                item = new WebMeta(searchValue);
                                item.Put("key", key);
                                break;
                            default:
                                item.Put("click", searchValue);
                                if ((search["Max"] ?? "").Contains("YES"))
                                {
                                    item.Put("max", true);

                                    foreach (var v in dataEvent)
                                    {
                                        var btn = v as Hashtable;
                                        btn.Remove("max");
                                    }
                                }
                                break;
                        }

                        item["text"] = search["text"];
                        item["icon"] = search["icon"];
                        if (index > -1 && index < dataEvent.Length)
                        {
                            dataEvent.SetValue(item, index);
                        }
                        else
                        {
                            var d = new ArrayList();
                            d.AddRange(dataEvent);
                            d.Add(item);
                            dataEvent = d.ToArray();
                        }
                        Config["footBar"] = dataEvent;

                        UMC.Data.DataFactory.Instance().Config(AppConfigKey, appConf);

                        this.Context.Send($"{request.Model}.{request.Command}.View", true);

                        //
                    }
                    break;
                case "Download":

                    var type = this.AsyncDialog("Type", r =>
                      {
                          var selt = new UISheetDialog() { Title = "应用下载" };
                          selt.Action(true);
                          selt.Put("Android", "Android");
                          selt.Put("IPhone", "IPhone");
                          return selt;
                      });
                    switch (type)
                    {
                        case "IPhone":
                            response.Redirect(new Uri("https://www.apiumc.com/umc/Home/IOS"));

                            break;
                        default:
                            response.Redirect(new Uri(request.Url, $"/UMC/app.html"));

                            break;
                    }

                    //("提交应用生成信息后，将需要一到两分钟后才会生成成功。") { Title = "下载提示", IsAction = true, SubmitText="去下载" });
                    break;
                default:
                    if (model.StartsWith("dataEvent."))
                    {
                        goto case "dataEvent";
                    }
                    else if (model.StartsWith("footBar."))
                    {
                        goto case "footBar";
                    }
                    break;//
            }
        }

    }

}